package com.tequila.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tequila.core.ErrorConstants;
import com.tequila.core.service.UserService;
import com.tequila.domain.dto.UserDto;
import com.tequila.domain.dto.wx.UserInfo;
import com.tequila.domain.dto.wx.WXUserDto;
import fe.core.ApiResponse;
import fe.core.Assert;
import fe.core.FastJson;
import fe.core.HttpClientUtils;
import fe.core.springmvc.BaseController;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by chengpanwang on 2017/7/3.
 */
@RestController
public class LoginController extends BaseController {

    public static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    private String wxLoginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=wx50c61e330be006be&secret=28ce186fc35954863d04a652b1ee0809&js_code=%s&grant_type=authorization_code";

    @Resource
    UserService userService;

    @RequestMapping("/wx/login")
    public ApiResponse login(WXUserDto wxUserDto) {
        logger.info("小程序用户登录：{}", JSON.toJSONString(wxUserDto));

        checkData(wxUserDto);
        UserDto userDto = updateUser(wxUserDto);

        return ApiResponse.successApiResponse(createUserDetail(userDto.getId(),null,null,false,userDto));
    }

    @RequestMapping("/wx/newLogin")
    public ApiResponse newLogin(WXUserDto wxUserDto) {
        logger.info("小程序用户登录：{}", JSON.toJSONString(wxUserDto));
        wxUserDto.setOpenid("-1");
        Map<String,Object> rowDataMap = new HashMap<String,Object>();
        rowDataMap.put("weChatOpenId","-1");
        rowDataMap.put("nickName","test");
        rowDataMap.put("avatarUrl","https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKoPAFGBEoyU5H8B12GicquFWOTSK9ZIUrQSNFaeKN02oudVwfR8WLDxp79VeOAhuAKjC96XV1F4LQ/0");
        wxUserDto.setRawData(FastJson.toJson(rowDataMap));
        UserDto userDto = updateUser(wxUserDto);
        return ApiResponse.successApiResponse(createUserDetail(userDto.getId(),null,null,false,userDto));
    }

    private UserDto updateUser(WXUserDto wxUserDto) {

        UserDto userDto = new UserDto();

        UserInfo userInfo = JSON.parseObject(wxUserDto.getRawData(), UserInfo.class);

        userDto.setWeChatOpenId(wxUserDto.getOpenid());
        userDto.setNickName(userInfo.getNickName());
        userDto.setAvatarUrl(userInfo.getAvatarUrl());
        userService.insertOrUpdate(userDto);

        return userDto;
    }

    private void checkData(WXUserDto wxUserDto) {

        String res = HttpClientUtils.post(String.format(wxLoginUrl, wxUserDto.getCode()));
        logger.info("获取小程序用户 openid, session key 结果: {}", res);
        Assert.assertNotNull(res, ErrorConstants.WX_LOGIN_ERR);
        JSONObject resData = JSON.parseObject(res);
        Assert.assertNotNull(res, ErrorConstants.WX_LOGIN_ERR);
        String openid = MapUtils.getString(resData, "openid");
        String sessionKey = MapUtils.getString(resData, "session_key");

        wxUserDto.setOpenid(openid);
        wxUserDto.setSessionKey(sessionKey);

        Assert.assertNotNull(openid, ErrorConstants.WX_LOGIN_ERR);
        Assert.assertNotNull(sessionKey, ErrorConstants.WX_LOGIN_ERR);

        String sign = DigestUtils.sha1Hex(wxUserDto.getRawData() + sessionKey);
        Assert.assertNotEquals(sign, wxUserDto.getSignature(), ErrorConstants.WX_LOGIN_SIGN_ERR);

        logger.info("校验小程用户登录信息");

    }
}
